package com.hw.hcit.feature;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Collections;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.media.MediaRouter.VolumeCallback;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.text.format.Formatter;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.os.storage.StorageManager;
import android.os.storage.StorageEventListener;
import android.os.storage.DiskInfo;
import android.os.storage.VolumeInfo;
import com.hw.hcit.R;
import com.hw.hcit.conf.Config;
import com.hw.hcit.conf.JTestItem;

public class SDCardTest extends JTestItem  {
   private static final String LOG_TAG = "SDCardTest ";
   private static String SD_CARD_PATH;
   private static final String TEST_FILE_NAME = "temp.txt";
   private static final String TEST_STRING = "1234567890ABCDEFGH";
   private StorageManager mStorageManager;
   private Context mContext;
   private String mResult;
   private VolumeInfo mVolume;
   private List<VolumeInfo> volumes;
   private String TOTAL_CAPACITY;
   private String USED_CAPACITY;
   private String SD_ABSENT;

   private static final int RESULT_CODE_SDCARD_ABSENT = 0;
   private static final int RESULT_CODE_WRITE_FAIL = 1;
   private static final int RESULT_CODE_READ_FAIL = 2;

   private TextView mTestResult;
   private int mResultCode;
   private String mResultStr;
   private boolean mPowerClicked;
   private Button mButton1, mButton2;

   private Handler mHandler = new Handler() {
      public void handleMessage(Message msg) {

         switch (msg.what) {
         case 0:
            mResult = mResult + "\n"
                  + getString(R.string.sdcard_test_success);
            mTestResult.setTextColor(Color.GREEN);
            mButton1.setEnabled(true);
            break;
         case 1:
            mResult = mResult + "\n"
                  + getString(R.string.sdcard_write_failed);
            mTestResult.setTextColor(Color.RED);
            mButton2.setEnabled(true);
         case 2:
            mResult = mResult + "\n"
                  + getString(R.string.sdcard_read_failed);
            mTestResult.setTextColor(Color.RED);
            mButton2.setEnabled(true);
            break;
         case 3:
            mResult = mResult + "\n"
                  + getString(R.string.sdcard_read_failed);
            mTestResult.setTextColor(Color.RED);
            mButton2.setEnabled(true);
            break;
         case 4:
             mTestResult.setTextColor(Color.RED);
             mButton2.setEnabled(true);
             break;
         default:
            break;
         }
         mTestResult.setText(mResult);
         mTestResult.setVisibility(View.VISIBLE);
      }
   };

   public SDCardTest() {
      super();
   }

   @Override
   public void onCreate(Bundle savedInstanceState) {
      // TODO Auto-generated method stub
      super.onCreate(savedInstanceState);
      mContext = Config.GetActivity().getApplicationContext();
      mStorageManager = mContext.getSystemService(StorageManager.class);
      volumes = mStorageManager.getVolumes();
   }

   @Override
   public View onCreateView(LayoutInflater inflater, ViewGroup container,
         Bundle savedInstanceState) {
      View rootView = inflater
            .inflate(R.layout.sdcard_test, container, false);
      TOTAL_CAPACITY = getString(R.string.total_capacity);
      USED_CAPACITY = getString(R.string.used_capacity);
      SD_ABSENT = getString(R.string.sdcard_absent);
      mTestResult = (TextView) rootView.findViewById(R.id.test_result);
      mButton1 = (Button) rootView.findViewById(R.id.button1);
      mButton2 = (Button) rootView.findViewById(R.id.button2);
      mButton1.setOnClickListener(new OnClickListener() {

         @Override
         public void onClick(View arg0) {
            // TODO Auto-generated method stub
            if (Config.CURR_PROJECT.isAuto()) {
               if (!Config.ageingTested) {
                  rewriteOneByteOfNv2499(1, 'P');

               } else {
                  rewriteOneByteOfNv2499(32, 'P');
               }
            }

            testFinish(true, 1, true);

         }
      });
      mButton2.setOnClickListener(new OnClickListener() {

         @Override
         public void onClick(View arg0) {
            // TODO Auto-generated method stub
            if (Config.CURR_PROJECT.isAuto()) {
               if (!Config.ageingTested) {
                  rewriteOneByteOfNv2499(1, 'F');

               } else {
                  rewriteOneByteOfNv2499(32, 'F');
               }
            }
            testFinish(false, 1, false);

         }
      });
      return rootView;
   }

   @Override
   public void onAttach(Activity activity) {
      // TODO Auto-generated method stub
      super.onAttach(activity);

   }

   @Override
   public boolean getResult() {
      // TODO Auto-generated method stub
      return false;
   }

   @Override
   public String getResultInfo() {
      // TODO Auto-generated method stub
      return null;
   }

   @Override
   public void startTest() {
      // TODO Auto-generated method stub
      // start to test
   }

   @Override
   public void stopTest() {
      // TODO Auto-generated method stub

   }

   @Override
   public void refresh() {
	   StringBuilder sBuilder = new StringBuilder();
      if (volumes != null) {
         Collections.sort(volumes, VolumeInfo.getDescriptionComparator());
         for (VolumeInfo vol : volumes) {
            if (vol.getType() == VolumeInfo.TYPE_PUBLIC) {
               mVolume = vol;
            }
         }
        if(mVolume !=null){
         if (mVolume.isMountedReadable()) {
            // TODO: move statfs() to background thread
            final File path = mVolume.getPath();
            SD_CARD_PATH = path.getPath();
            final long freeBytes = path.getFreeSpace();
            final long totalBytes = path.getTotalSpace();
            final long usedBytes = totalBytes - freeBytes;
            final String title = mStorageManager
                  .getBestVolumeDescription(mVolume);
            final String used = Formatter.formatFileSize(mContext,
                  usedBytes);
            final String total = Formatter.formatFileSize(mContext,
                  totalBytes);
            Log.d("XX", "used =" + used + "\n" + "total =" + total + "\n"
                  + "path  =" + path.getPath());
            sBuilder = sBuilder.append(title).append("\n");
            sBuilder = sBuilder.append(TOTAL_CAPACITY).append(total).append("\n");
            sBuilder = sBuilder.append(USED_CAPACITY).append(used);
            mResult = sBuilder.toString();
            if (!writeTestFile()) {
               mHandler.sendEmptyMessage(1);
            } else if (!readTestFile() || !compareTestFile(mResultStr)) {
               mHandler.sendEmptyMessage(2);
            } else {
               mHandler.sendEmptyMessage(0);
            }
         } else {
            mResult = getString(mVolume.getStateDescription());
         }
        }else{
        	sBuilder = sBuilder.append(SD_ABSENT);
        	mResult = sBuilder.toString();
        	mHandler.sendEmptyMessage(4);
        }
      }
   }

   @Override
   public void onResume() {
      // TODO Auto-generated method stub
      super.onResume();
      mButton1.setEnabled(false);
      mButton2.setEnabled(false);
      mResultCode = -1;
      mPowerClicked = false;
      refresh();
   }

   @Override
   public void onPause() {
      // TODO Auto-generated method stub
      super.onPause();
      mHandler.removeMessages(0);
      mHandler.removeMessages(1);
      mHandler.removeMessages(2);
      mHandler.removeMessages(3);
      mHandler.removeMessages(4);
      mResultCode = -1;
      mResultStr = null;
   }

   private boolean writeTestFile() {
      try {
         File file = new File(SD_CARD_PATH, TEST_FILE_NAME);
         if (!file.exists())
            file.createNewFile();
         FileOutputStream fos = new FileOutputStream(file);

         if (file.canWrite()) {
            fos.write(TEST_STRING.getBytes());
            fos.close();
         }
      } catch (Exception exception) {
         mResultCode = RESULT_CODE_WRITE_FAIL;
         Log.e(LOG_TAG, LOG_TAG + exception.getLocalizedMessage());
         return false;
      }
      return true;
   }

   private boolean readTestFile() {
      try {
         File file = new File(SD_CARD_PATH, TEST_FILE_NAME);
         FileInputStream fis = new FileInputStream(file);
         int length = (int) file.length();
         byte[] bytes = new byte[length];
         fis.read(bytes);
         mResultStr = new String(bytes);
         fis.close();
         file.delete();
         return true;
      } catch (Exception exception) {
         mResultCode = RESULT_CODE_READ_FAIL;
         Log.e(LOG_TAG, LOG_TAG + exception.getLocalizedMessage());
         return false;
      }
   }

   private boolean compareTestFile(String str) {
      if (!TextUtils.isEmpty(mResultStr)) {
         if (TEST_STRING.equals(mResultStr)) {
            return true;
         }
      }
      mResultCode = RESULT_CODE_READ_FAIL;
      return false;
   }

   @Override
   public boolean dispatchKeyEvent(KeyEvent event) {
      // TODO Auto-generated method stub
      return true;
   }
}
